package algorithm.leetcode

object TopLeaseMatrix {

    //笨方法
    fun isTopMatrix(row : Int, column : Int, ar : IntArray) : Boolean{

        if(row * column != ar.size) return false
        var k = 0
        for (i in column-2 downTo 0){
            var sample = 0
            k = i
            for (j in 0 until row) {
                var ret = 1f
                if(j == 0){
                    sample = ar[j*column + i]
                }else{
                    k += 1
                    if(k <= column-1){
                        ret = sample.toFloat() / ar[j*column + k]
                    }
                }
                if(ret != 1f){
                    return false
                }
            }
        }

        var sample = 0
        for (j in 1 until row-1){
            var ret = 1f
            var c = 0
            if(j == 1){
                sample = ar[j*column + c]
            }else{
                c += 1
                if(c < k){
                    ret = sample.toFloat() / ar[j*column + c]
                }
            }
            if(ret != 1f){
                return false
            }
        }

        return true
    }

    fun isTopMatrix2(row : Int, column : Int, ar : IntArray) : Boolean{
        if(row * column != ar.size) return false

        for (r in 0 until row){
            for (c in 0 until column){
                if(r+1 < row && c+1 < column){
                    val ret = ar[r * column + c] == ar[(r+1) * column + c+1]
                    if(!ret) return false
                }
            }
        }
        return true
    }

    fun isToeplitzMatrix(matrix: Array<IntArray>): Boolean {
        val row = matrix.size
        val column = matrix[0].size
        for (r in 0 until row){
            for (c in 0 until column){
                if(r+1 < row && c+1 < column){
                    val ret = matrix[r][c] == matrix[(r+1)][c+1]
                    if(!ret) return false
                }
            }
        }
        return true
    }
}

fun main() {
    val ar = intArrayOf(
        1, 2, 3, 4,
        5, 1, 2, 3,
        9, 5, 1, 2
    )
    print(TopLeaseMatrix.isTopMatrix2(3, 4, ar))
}